package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class OrderTradeStrategyContext implements ApplicationContextAware {

    // 定义一个Map类型成员变量，用来管理OrderTradeStrategy这个接口的实现类对象
    // Map的键就是itemType，值就是OrderTradeStrategy这个接口的实现类对象
    private static final Map<String , OrderTradeStrategy> ORDER_TRADE_STRATEGY_MAP = new ConcurrentHashMap<>() ;

    // 根据itemTyp获取对应的策略接口实现对象的方法
    public static OrderTradeStrategy getOrderTradeStrategy(String itemType) {
        return ORDER_TRADE_STRATEGY_MAP.get(itemType) ;
    }

    /**
     * 该方法是有框架帮我们进行调用的
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        /**
         * beansOfType方法返回的是一个Map，Map的键就是bean名称，值就是bean对象
         */
        Map<String, OrderTradeStrategy> beansOfType = applicationContext.getBeansOfType(OrderTradeStrategy.class);
        beansOfType.values().forEach(orderTradeStrategy -> {
            String itemType = orderTradeStrategy.getItemType();
            ORDER_TRADE_STRATEGY_MAP.put(itemType , orderTradeStrategy) ;
        });

        log.info("OrderTradeStrategy策略实现类的对象进行了统计的管理....");

    }

}
